package org.jeese.modules.demo.web;

import java.util.HashMap;
import java.util.Map;

import org.jeese.common.base.service.RedisService;
import org.jeese.common.bean.ResponseResult;
import org.jeese.modules.sys.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/")
public class RedisController {
	@Autowired
	private RedisService redisService;

	@RequestMapping("/redis/set")
	public ResponseResult redisSet(@RequestParam(value = "value", required = true) String value) {
		ResponseResult result = new ResponseResult();
		boolean isOk = redisService.set("name", value);
		if(isOk){
			result.success();
		} else {
			result.fail();
		}
		return result;
	}

	@RequestMapping("/redis/get")
	public ResponseResult redisGet(@RequestParam(value = "key", required = true) String key) {
		ResponseResult result = new ResponseResult();
		String name = redisService.get(key);
		if(!StringUtils.isEmpty(name)){
			result.successData(name);
		} else {
			result.fail();
		}
		return result;
	}
	
	@RequestMapping("/redis/del")
	public ResponseResult redisDel(@RequestParam(value = "key", required = true) String key) {
		ResponseResult result = new ResponseResult();
		long flag = redisService.del(key);
		if (flag > 0) {
			result.success();
		} else {
			result.fail();
		}
		return result;
	}
	
	@RequestMapping("/redis/exists")
	public ResponseResult exists(@RequestParam(value = "key", required = true) String key) {
		ResponseResult result = new ResponseResult();
		boolean flag = redisService.exists(key);
		if(flag){
			result.success();
		} else {
			result.fail();
		}
		return result;
	}
	
	@RequestMapping("/redis/setMap")
	public ResponseResult setMap() {
		ResponseResult result = new ResponseResult();
		Map<String, String> map = new HashMap<String, String>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");
		Map<String, SysUser> usermap = new HashMap<String, SysUser>();
		SysUser user = new SysUser();
		user.setUserId(1L);
		user.setAccount("admin");
		usermap.put("1", user);
		usermap.put("2", user);
		boolean isOk = redisService.setMap("testMap", usermap);
		if(isOk){
			result.success();
		} else {
			result.fail();
		}
		return result;
	}
	
	@RequestMapping("/redis/getMap")
	public ResponseResult getMap(@RequestParam(value = "key", required = true) String key) {
		ResponseResult result = new ResponseResult();
		Map<String, SysUser> map = redisService.getMap(key);
		if (map != null && map.size() > 0) {
			result.successData(map);
		} else {
			result.fail();
		}
		return result;
	}
}
